#ifndef WEATHERTOOL_H
#define WEATHERTOOL_H

#include <QTextCodec>
#include <QDebug>
#include <QMap>
#include <QJsonParseError>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonDocument>
#include <QFile>
#include <QByteArray>
class WeatherTool
{
private:
    static QMap<QString,QString>wCityMap;
public:
    WeatherTool() {}
    static void initWCityMap()
    {
        QFile file("E:/interview_QTprojects/weather_me/citycode-2019-08-23.json");
        if(file.open(QIODevice::ReadOnly|QIODevice::Text))
        {
            qDebug()<<"正确";
        }
        QByteArray byteArray=file.readAll();
        file.close();
        QJsonParseError error;
        QJsonDocument doc=QJsonDocument::fromJson(byteArray,&error);
        if(error.error!=QJsonParseError::NoError)
        {
            qDebug()<<"QJsonParseError";
            return;
        }
        if(!doc.isArray())
        {
            qDebug()<<"not qjsonarray";
            return;
        }
        QJsonArray array=doc.array();
        qDebug()<<"city_name:"<<array.at(0).toObject().value("city_name").toString();
        for(int i=0;i<array.size();i++)
        {
            QString cityName=array.at(i).toObject().value("city_name").toString();
            QString cityCode=array.at(i).toObject().value("city_code").toString();
            if(cityCode.size()==0)
            {
                continue;
            }
            wCityMap.insert(cityName,cityCode);
        }

    }
    static QString getCityCode(QString cityName)
    {
        QMap<QString,QString>::iterator it=wCityMap.find(cityName);
        if(it==wCityMap.end())
        {
            QMap<QString,QString>::iterator it1=wCityMap.find(cityName+"市");
            if(it1==wCityMap.end())
            {
                return "";
            }
            return wCityMap.value(cityName+"市");
        }
        return wCityMap.value(cityName);

    }
};
QMap<QString,QString> WeatherTool::wCityMap={};

#endif // WEATHERTOOL_H
